from flask import current_app, request
from flask_restx import abort, reqparse

from app.api.v1.participant.base_view import ParticipantBase
from app.models import courseModel, userModel
from tools import db
from utils.utils import base_detail


class MyCourseList(ParticipantBase):
    def get_system_list(self, page, page_size, _filters):
        paginate = (
            courseModel.Course.query.filter(*_filters)
            .filter_by(isSystem=1)
            .order_by(courseModel.Course.id.desc())
            .paginate(page, page_size, error_out=False)
        )
        info = {
            "data": [],
            "current_page": page,
        }
        if len(paginate.items) > 0:
            for content in paginate.items:
                info["data"].append(
                    [{"course_name": content.name, "course_uuid": content.id}]
                )

        info = base_detail(info, paginate)
        return {"code": 200, "data": info}

    def get_list(self, page, page_size, _filters):
        paginate = (
            self.user.courses.filter(*_filters)
            .filter_by(status="1")
            .order_by(courseModel.Course.id.desc())
            .paginate(page, page_size, error_out=False)
        )
        info = {
            "data": [],
            "current_page": page,
        }
        if len(paginate.items) > 0:
            for content in paginate.items:
                info["data"].append(content.to_dict())

        info = base_detail(info, paginate)
        return {"code": 200, "data": info}

    def get(self, is_system=None):

        params = request.args
        page = params.get("page", type=int, default=1)
        page_size = params.get("pageSize", type=int, default=10)
        keyword = params.get("keyword", type=str)

        _filters = []
        if keyword:
            _filters.append(courseModel.Course.name.contains(keyword))
        try:
            if is_system:
                return self.get_system_list(page, page_size, _filters)
            else:
                return self.get_list(page, page_size, _filters)
        except Exception as e:
            current_app.logger.exception(e)
            abort(500, message="获取失败")


class MyCourseManage(ParticipantBase):
    def get(self, uuid=None, is_system=None):
        try:
            if is_system:
                course_info = courseModel.Course.query.filter_by(
                    id=uuid, isSystem=1
                ).first()
            else:
                course_info = courseModel.Course.query.filter_by(
                    id=uuid, status="1"
                ).first()

            if not course_info:
                return {"code": 200, "data": []}

            course_info_dict = course_info.to_status_dict()
            if "chapter_coursewares" in course_info_dict:
                for chapter in course_info_dict["chapter_coursewares"]:
                    if "child" in chapter:
                        for courseware in chapter["child"][::-1]:
                            if courseware["range_uuid"] is None:
                                continue
                            if courseware["env_status"] == "0" and not is_system:
                                chapter["child"].remove(courseware)
            return {"code": 200, "data": course_info_dict}

        except Exception as e:
            current_app.logger.exception(e)
            abort(500, message="参数错误")


class MyCourseWareList(ParticipantBase):
    def get(self, uuid=None):
        try:
            course_info = courseModel.Course.query.filter_by(
                id=uuid, status="1"
            ).first()
            chapter_info = [_.to_dict() for _ in course_info.chapter_set.all()]
            courseware_resources = []
            for chapter in chapter_info:
                if "child" in chapter and len(chapter["child"]) > 0:
                    for courseware in chapter["child"]:
                        if (
                            "videoPath" in courseware
                            and courseware["videoPath"] is not None
                        ):
                            courseware_resources.append(courseware)
            return {"code": 200, "data": courseware_resources}

        except Exception as e:
            current_app.logger.exception(e)
            abort(500, message="参数错误")


class MemberPassword(ParticipantBase):
    """
    修改个人密码
    since: 21.12.28
    """

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("password", help="请输入密码", required=True)
        parser.add_argument("confirm_password", help="输入确认密码", required=True)
        args = parser.parse_args()

        if not all([args["password"], args["confirm_password"]]):
            abort(400, message="参数错误")

        if args["password"] != args["confirm_password"]:
            abort(400, message="两次密码不一致")

        with db.auto_commit():
            self.user.password = args["password"]
            userModel.db.session.commit()
            current_app.logger.info(
                f"{self.user.username}---action--MemberPassword--user:{self.user.id}"
            )
        return {"code": 200, "data": "密码修改成功"}
